package com.dw.dao.impl;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.springframework.stereotype.Repository;

import com.dw.dao.UserDao;
import com.dw.entity.User;
import com.dw.utils.HibernateSessionFactory;

@SuppressWarnings("unchecked")
@Repository
public class IUserDao implements UserDao{

	@Override
	public List<User> getAllUser() {
		Session session = HibernateSessionFactory.getSession();
		List<User> userList = new ArrayList<User>();

		Transaction tran = session.beginTransaction();
		String hql = "from User";

		Query query = session.createQuery(hql);

		userList = query.list();
		
		tran.commit();
		HibernateSessionFactory.closeSession(session);
		return userList;
	}

	@Override
	public void addUser(User user) {
		Session session = HibernateSessionFactory.getSession();

		Transaction tran = session.beginTransaction();
		session.save(user);
		tran.commit();
		HibernateSessionFactory.closeSession(session);
	}

	@Override
	public User findById(int id) {
		Session session = HibernateSessionFactory.getSession();

		Transaction tran = session.beginTransaction();
		String hql = "from User where id="+id;
		Query query = session.createQuery(hql);
		User user = (User) query.uniqueResult();
		tran.commit();
		HibernateSessionFactory.closeSession(session);
		return user;
	}

}
